﻿using HandyControl.Controls;
using HandyControl.Interactivity;
using Microsoft.Win32;
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace LpbPrj.Client.Controls;

public class ImageUriSelectorEx : ImageSelector
{
    public ImageUriSelectorEx()
    {
        CommandBindings.Add(new CommandBinding(ControlCommands.Selected, SelectedImage));
        SetCurrentValue(FilterProperty, "(.png)|*.png|(.jpg)|*.jpg");
        SetCurrentValue(DefaultExtProperty, ".png");
    }

    private void SelectedImage(object sender, ExecutedRoutedEventArgs e)
    {
        if (!HasValue)
        {
            var dialog = new OpenFileDialog
            {
                RestoreDirectory = true,
                Filter = Filter,
                DefaultExt = DefaultExt
            };

            if (dialog.ShowDialog() == true)
            {
                SetCurrentValue(UriExProperty, new Uri(dialog.FileName, UriKind.RelativeOrAbsolute));
            }
        }
        else
        {
            SetCurrentValue(UriExProperty, default(Uri));
        }
    }

    public static readonly DependencyProperty UriExProperty = DependencyProperty.Register(
        nameof(UriEx), typeof(Uri), typeof(ImageUriSelectorEx), new FrameworkPropertyMetadata(default(Uri), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnUriExChangedCallback));
    private static void OnUriExChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d == null) return;
        ImageUriSelectorEx edit = (ImageUriSelectorEx)d;
        if (edit == null) return;

        if (e.NewValue is Uri uri)
        {
            edit.SetValue(UriPropertyKey, uri);
            edit.SetValue(PreviewBrushPropertyKey, new ImageBrush(BitmapFrame.Create(uri)) { Stretch = edit.Stretch });
            edit.SetValue(HasValuePropertyKey, true);
            edit.SetCurrentValue(ToolTipProperty, uri);

            edit.RaiseEvent(new RoutedEventArgs(ImageSelectedEvent, edit));
        }
        else
        {
            edit.SetValue(UriPropertyKey, default);
            edit.SetValue(PreviewBrushPropertyKey, default);
            edit.SetValue(HasValuePropertyKey, false);
            edit.SetCurrentValue(ToolTipProperty, default);

            edit.RaiseEvent(new RoutedEventArgs(ImageSelectedEvent, edit));
        }
    }
    public Uri UriEx
    {
        get => (Uri)GetValue(UriExProperty);
        set => SetValue(UriExProperty, value);
    }

}
